package com.mdd.front.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.core.PageResult;
import com.mdd.common.dto.result.OrderPageResultDto;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.salesman.Salesman;
import com.mdd.common.exception.OperateException;
import com.mdd.common.utils.SnUtils;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.order.IOrderService;
import com.mdd.front.service.refund.IOrderRefundService;
import com.mdd.front.service.salesman.ISalesmanService;
import com.mdd.front.service.system.ISystemDevPayWayService;
import com.mdd.front.validate.PageParam;
import com.mdd.front.validate.order.OrderCancelParam;
import com.mdd.front.validate.order.OrderPageParam;
import com.mdd.front.validate.order.OrderParam;
import com.mdd.front.vo.goods.OrderGoodsDetailVo;
import com.mdd.front.vo.order.OrderDetailVo;
import com.mdd.front.vo.order.OrderListVo;
import com.mdd.front.vo.refund.OrderRefundDetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;

/**
 * 订单管理
 */
@Api(tags = "订单管理")
@Slf4j
@RestController
@RequestMapping("api/order")
public class OrderController {

	@Resource
	IOrderService iOrderService;

	@Resource
	private ISystemDevPayWayService systemDevPayWayService;
	@Resource
	private IOrderRefundService iOrderRefundService;

	@Resource
	private ISalesmanService iSalesmanService;

	/**
	 * 订单列表
	 *
	 * @param pageParam 分页参数
	 * @param params    搜索参数
	 * @return Object
	 */
	@ApiOperation(value = "订单管理 - 列表")
	@GetMapping("/list")
	public PageResult<OrderListVo> list(@Validated PageParam pageParam,
	                                    @RequestParam Map<String, String> params) {
		params.put("userId", LikeFrontThreadLocal.getUserId() + "");
		return iOrderService.list(pageParam, params);
	}

	@ApiOperation(value = "订单管理 - 待评价列表")
	@GetMapping("/wait/comment/list")
	public PageResult<OrderPageResultDto> listWaitComment(@Validated PageParam pageParam,
	                                                      @RequestParam Map<String, String> params) {
		params.put("userId", LikeFrontThreadLocal.getUserId() + "");
		return iOrderService.listWaitComment(pageParam, params);
	}

	/**
	 * 师傅订单列表
	 *
	 * @param pageParam 分页参数
	 * @param params    搜索参数
	 * @return Object
	 */
	@ApiOperation(value = "订单管理 - 师傅订单列表")
	@GetMapping("/staff/list")
	public PageResult<OrderListVo> staffOrderList(@Validated PageParam pageParam,
	                                              @RequestParam Map<String, String> params) {
		params.put("userId", LikeFrontThreadLocal.getUserId() + "");
		return iOrderService.staffOrderList(pageParam, params);
	}

	/**
	 * 订单详情
	 *
	 * @param id 主键ID
	 * @return Object
	 */
	@ApiOperation(value = "订单管理 - 订单详情")
	@GetMapping("/detail")
	public OrderDetailVo detail(@Validated @RequestParam("id") Integer id) {
		return iOrderService.detail(id);
	}

	/**
	 * 订单新增
	 *
	 * @param orderParam 参数
	 * @return Object
	 */
	@ApiOperation(value = "订单管理 - 订单新增")
	@PostMapping("/add")
	public Order add(@Validated(value = OrderParam.create.class) @RequestBody OrderParam orderParam) {
		Long userId = LikeFrontThreadLocal.getUserId().longValue();
		orderParam.setUserId(userId);
		return iOrderService.add(orderParam);
	}

	/**
	 * 订单新增
	 *
	 * @param orderParam 参数
	 * @return Object
	 */
	@ApiOperation(value = "订单管理 - 订单新增")
	@PostMapping("/update")
	public Order update(@Validated(value = OrderParam.create.class) @RequestBody OrderParam orderParam) {
		Long userId = LikeFrontThreadLocal.getUserId().longValue();
		orderParam.setUserId(userId);
		return iOrderService.update(orderParam);
	}

	/**
	 * 订单初始化
	 *
	 * @param goodsId 参数 传规格ID 即可
	 * @return Object
	 */
	@ApiOperation(value = "订单管理 - 订单初始化")
	@GetMapping("/init")
	public OrderGoodsDetailVo initOrder(@RequestParam("goodsId") Long goodsId, @RequestParam("goodsNum") Integer goodsNum, @RequestParam(value = "isBuyFlag", required = false) Integer isBuyFlag) {
		Long userId = LikeFrontThreadLocal.getUserId().longValue();
		return iOrderService.initOrder(userId, goodsNum, goodsId,isBuyFlag);
	}

	/**
	 * 用户取消订单 将已付款金额退还给用户
	 *
	 * @return Object
	 */
	@Deprecated
	@ApiOperation(value = "订单管理 - 取消订单")
	@PostMapping("/cancel")
	public void cancelOrder(@Validated @RequestBody OrderCancelParam param) throws Exception {
		Long userId = Long.valueOf(LikeFrontThreadLocal.getUserId());
		//该方法是为原方法
		//iOrderService.cancelOrder(param.getId(), userId, param.getSource());
		String sn = SnUtils.getRefundOrderSn();
		iOrderService.cancelOrder(param.getId(), userId, 0, sn);
	}

	/**
	 * 师傅确认服务
	 *
	 * @return Object
	 */
	@ApiOperation(value = "订单管理 - 师傅确认服务")
	@GetMapping("/staff/confirm")
	public void confirmGoods(@Validated @RequestParam("id") Long id) {
		Long userId = LikeFrontThreadLocal.getUserId().longValue();
		iOrderService.confirmGoods(id, userId);
	}

	/**
	 * 师傅核销服务订单
	 *
	 * @return Object
	 */
	@ApiOperation(value = "订单管理 - 师傅核销服务订单")
	@GetMapping("/staff/verification")
	public void confirmGoods(@Validated @RequestParam("id") Long id, @RequestParam(name = "code", required = false) String code) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		iOrderService.verificationOrder(id, userId, code);
	}

	/**
	 * 订单删除
	 *
	 * @param id 订单id
	 * @return Object
	 */
	@ApiOperation(value = "订单管理 - 删除")
	@GetMapping("/del")
	public void del(@RequestParam("id") Long id) {
		iOrderService.del(id);
	}

	@ApiOperation(value = "订单管理 - 订单支付状态")
	@GetMapping("/pay/status")
	public Order payStatus(@RequestParam("id") Long id) throws Exception {
		return iOrderService.payStatus(id);
	}

	/**
	 * 订单支付方式列表
	 *
	 * @param
	 * @return Object
	 * @author
	 */
	@GetMapping("/pay/way/list")
	public Object listPayWay(@RequestParam("scene") Integer scene,
	                         @RequestParam("orderId") Integer orderId,
	                         @RequestParam("type") String type) {
		Assert.notNull(orderId, "orderId不能为空");
		Assert.notNull(type, "type不能为空");
		Map<String, Object> list = systemDevPayWayService.list(scene, orderId, type);
		return AjaxResult.success(list);
	}

	/**
	 * 部分退款-用户进行部分退款
	 */
	@ApiOperation(value = "部分退款-用户进行部分退款")
	@GetMapping("/rebates")
	public void rebates(@RequestParam("orderId") Long orderId,
						@RequestParam(value = "refundId")Long refundId,
						@RequestParam(value = "refundAmount", required = true) BigDecimal refundAmount,
						@RequestParam(value = "remark", required = true) String remark){
		iOrderRefundService.rebates(orderId,refundId,refundAmount,remark);
	}

	@ApiOperation(value = "退款订单-通过订单id")
	@GetMapping("/getOrderRefund")
	public Object getOrderRefund(@RequestParam("orderId") Long orderId){
		OrderRefundDetailVo orderRefund =  iOrderRefundService.getOrderRefund(orderId);
		return AjaxResult.success(orderRefund);
	}


	@ApiModelProperty(value = "推销员 - 订单查询")
		@PostMapping("/referrersOrderList")
	public PageResult<OrderListVo> referrersOrderList(@RequestBody OrderPageParam params) {
		// 获取当前的用户
		Integer adminId = LikeFrontThreadLocal.getUserId();
		QueryWrapper<Salesman> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", adminId);
		wrapper.eq("is_delete", 0);
		Salesman one = iSalesmanService.getOne(wrapper);
		if(Objects.isNull(one)) {
			return null;
		}
		params.setSalesmanUserId(adminId);
		PageParam pageParam = new PageParam();
		pageParam.setPageNo(params.getPageNo());
		pageParam.setPageSize(params.getPageSize());
		Map<String, Object> stringObjectMap = BeanUtil.beanToMap(params);
		stringObjectMap.put("user_id", one.getUserId());
		return iOrderService.listSalesman(pageParam, stringObjectMap);
	}

	@ApiModelProperty("给指定的电话进行生成虚拟号码")
	@PostMapping("/callStaffPhone")
	public String callUserPhone(@RequestBody Map<String, String> map) throws ExecutionException, InterruptedException {
		return iOrderService.callUserPhone(map);
	}

	@ApiModelProperty("查询当前用户的团购信息的订单")
	@GetMapping("/getBuyOrder")
	public List<OrderListVo> getBuyOrder(@RequestParam Long orderId) {
		return iOrderService.getBuyOrder(orderId, LikeFrontThreadLocal.getUserId());
	}

	@ApiModelProperty("推销员创建新的团购订单")
	@GetMapping("/createBuyOrder")
	public Object createBuyOrder(@RequestParam(value = "goodsId") Integer goodsId) {
		// 获取当前的用户
		Integer adminId = LikeFrontThreadLocal.getUserId();
		QueryWrapper<Salesman> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", adminId);
		wrapper.eq("is_delete", 0);
		Salesman one = iSalesmanService.getOne(wrapper);
		if(Objects.isNull(one)) {
			throw new OperateException("不是推销员，不能生成团购订单");
		}
		return AjaxResult.success((Object) iOrderService.createBuyOrder(adminId, goodsId));
	}

}
